package com.aolong.archives.common.tag;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import com.aolong.archives.common.resource.I18nBundleUtil;
import com.aolong.archives.common.resource.ParameterUtil;

import static com.rock.platform.util.SessionUtils.SKEY_LANGUAGE;

public class ResourceTag extends SimpleTagSupport {

	private String key;
	private String language;
	
	private void setNewLanguage()
	{
		if (language == null || language.length() == 0)
		{
			Object oLanguage = getJspContext().getAttribute(SKEY_LANGUAGE,PageContext.SESSION_SCOPE);
			if (oLanguage == null)
			{
				PageContext pageContext = (PageContext)getJspContext();
				HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
				Cookie[] cookies = request.getCookies();
				if (cookies != null)
				{
					for(Cookie c : cookies)
					{
						if (c.getName().equals("language"))
						{
							language = c.getValue();
							break;
						}
					}
				}
				if (language == null || language.length() == 0)
				{
					language = ParameterUtil.getParameter("language");
				}
			}
			else
			{
				language = oLanguage.toString();
			}
		}
	}
	
	public void doTag() throws JspException, IOException
	{
		setNewLanguage();
		
		String text = I18nBundleUtil.getInstance().getString(key, language);
		
		getJspContext().getOut().write(text == null ? key : text);
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public String getLanguage() {
		return language;
	}

	public void setLanguage(String language) {
		this.language = language;
	}
}
